package com.why.controller;

import com.why.util.UserContextHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/aaa")
    public String test() {
        String uuid = UUID.randomUUID().toString();
        //top1 根据用户id设置锁，过期时间30秒
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("game_money_lock", uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            try {
                return "";
            } finally {
                // top1 删除也必须是原子操作 Lua脚本操作 删除成功返回1 否则返回0
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Integer lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Integer>(script, Integer.class), Arrays.asList("game_money_lock"), uuid);
            }

        } else {
            // 重试加锁
            try {
                // 登上两百毫秒
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return "";
        }
    }

    @GetMapping("/username")
    public String username() {
        String username = UserContextHolder.getInstance().getUsername();
        return username;
    }

}
